import { Injectable, ForbiddenException } from '@nestjs/common'
import { Model } from 'mongoose'
import { InjectModel } from '@nestjs/mongoose'
import { Group } from './schemas/group.schema'
import { CreateGroupDto } from './dto/create-group.dto'
import { GroupDto } from './dto/group.dto'
import { randomUUID } from 'node:crypto'

@Injectable()
export class GroupsService {
	constructor(@InjectModel(Group.name) private groupModel : Model<Group>) {}

	async insertMany(data: CreateGroupDto[]) : Promise<any> {
		for (const item of data) {
			const group: any = item
			const info = (await this.groupModel
				.findOne({ name: group.name })
				.exec())?.toObject()
			if (info) throw new ForbiddenException('已存在')
			else group.id = randomUUID()
		}
		const created = this.groupModel.insertMany(data)
		return created
	}

	async find() : Promise<Group[]> {
		return this.groupModel.find().exec()
	}

	async findOne(data: GroupDto) : Promise<any> {
		return this.groupModel.findOne(data).exec()
	}

	async updateOne(data: any) {
		const _id = data._id
		Reflect.deleteProperty(data, '_id')
		return this.groupModel.updateOne({ _id }, { $set: data }).exec()
	}

	async deleteOne(data: any) {
		if (data) {
			const deleted = await this.groupModel.deleteOne(data).exec()
			return deleted
		}
	}
}